package com.example.m1.controller;

import com.example.service1.common.api.M2Service;
import com.example.service1.common.pojo.M1;
import com.example.m1.service.M1Service;
import com.example.service1.common.api.entity.ResponseResult;
import com.example.service1.common.pojo.M2;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransactionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/m1")

public class M1Controller {

    @Autowired
    M1Service m1Service;
    @Autowired
    M2Service m2Service;

//    @Transactional
    @GlobalTransactional(name = "m12",rollbackFor = Exception.class)
    @GetMapping("/update/info")
    public ResponseResult<M1> updateM1() throws TransactionException {
        M1 m1 = m1Service.updateInfo(M1.defaultCreate());
//        GlobalTransactionContext.reload(RootContext.getXID()).rollback();
        ResponseResult<M2> m2ResponseResult = m2Service.updateM2();
        System.out.println(m2ResponseResult);
        /**
         * 分布式事务失效：
         * 1.xid为null
         * 2.同一个分布式事务中各参与者的xid不一样
         * 3.分布式表有脏数据undo_log等
         * 4.Fegin调用使用了Fallback降级或抛出的异常被全局处理
         */
        System.out.println(RootContext.getXID());
        int i=10/0;
        return ResponseResult.success(m1);
    }
}
